package org.mch.func.db.field;

import java.awt.event.ActionEvent;

import org.apache.commons.dbutils.QueryRunner;
import org.mch.biz.ui.FuncEvent;
import org.mch.func.cons.ConsDB;
import org.mch.func.db.tool.DBInfoUtil;

/**
 * 描述：
 * 
 * @author MCH；Date：2008-10-01；<BR/>
 * 
 */
public class DBFieldEvent extends FuncEvent {
	private static final long serialVersionUID = 1L;

	public DBFieldEvent() {
		super(null);
	}

	public DBFieldEvent(DBFieldPanel panel) {
		super(panel);
	}

	protected void onButtonClick(ActionEvent e) throws Exception {
		if (e.getSource() == getPanel().getBtnExecute()) {
			execute();
		} else if (e.getSource() == getPanel().getBtn_loadtable()) {
			loadDBTables();
		}
	}

	protected void execute() throws Exception {
		if (getPanel().getChckbx_modifyfield().isSelected()) {
			modifyTableField();
		}
	}

	protected void loadDBTables() throws Exception {
		String[] ss = DBInfoUtil.getUserTables().toArray(new String[0]);
		getPanel().getListToList().setLeftData(ss);
	}

	protected void modifyTableField() throws Exception {
		Object[] seltabs = getPanel().getListToList().getRightData();
		String oldfield = getPanel().getText_oldfield().getText();
		String newfield = getPanel().getText_newfield().getText();

		QueryRunner run = new QueryRunner();
		for (int i = 0, len = seltabs.length; i < len; i++) {
			StringBuilder sb = new StringBuilder();
			sb.append("alter table ");
			sb.append(seltabs[i]);
			sb.append(" rename column ");
			sb.append(oldfield);
			sb.append(" to ");
			sb.append(newfield);
			sb.append("");
			run.update(ConsDB.conn, sb.toString());
		}

	}

	public DBFieldPanel getPanel() {
		return (DBFieldPanel) super.getPanel();
	}
}